package com.ask.pcb.product.generator.service.impl;

import com.ask.pcb.product.generator.dao.CategoryDao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ask.pcb.product.common.utils.PageUtils;
import com.ask.pcb.product.common.utils.Query;

import com.ask.pcb.product.generator.entity.CategoryEntity;
import com.ask.pcb.product.generator.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities=baseMapper.selectList(null);
        return  entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() ==0
        ).map(mean ->{
            mean.setChildMean(getChildMean(mean,entities));
            return  mean;
        }).sorted((mean1,mean2)->{
            return  (mean1.getSort() == null ?0:mean1.getSort()) - (mean2.getSort()==null ? 0 : mean2.getSort());
        }).collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList){
        //TODO  1逻辑删除方法
        baseMapper.deleteBatchIds(asList);
    }

    private List<CategoryEntity> getChildMean(CategoryEntity mean, List<CategoryEntity> entities) {
        return entities.stream().filter(categoryEntity ->
            categoryEntity.getParentCid() == mean.getCatId()
        ).map(categoryEntity -> {
            categoryEntity.setChildMean(getChildMean(categoryEntity,entities));
            return  categoryEntity;
        }).sorted((mean1,mean2)->{
            return  (mean1.getSort() == null ?0:mean1.getSort()) - (mean2.getSort()==null ? 0 : mean2.getSort());
        }).collect(Collectors.toList());

    }

}